﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DMS.Business.Modules.ArchivesManagement;
using DMS.Business.Utility;
using DMS.Business.Modules.Organization;
using DMS.Data.Modules.ArchivesManagement;

namespace DMS.Web.Modules.ArchivesManagement
{
    public partial class ZHArchInfoList : System.Web.UI.Page
    {
        #region 属性
        
        private AuthenticationUser _loginUser;
        private AuthenticationUser LoginUser
        {
            get
            {
                if (_loginUser == null)
                {
                    _loginUser = SystemContext.Current.LoginAuthUser;
                }
                return _loginUser;
            }
        }

        private IQueryable<ZHArchInfo> ZHArchInfos { get; set; }

        /// <summary>
        /// 预警
        /// </summary>
        private int DelayWarning
        {
            get { return int.Parse(ConfigHelper.GetSysConfigByID("DelayWarning").Value); }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitControls();
                Search();
            }
            //CurrentPage.Checked = false;
        }

        private void InitControls()
        {
            if (!SystemContext.Current.LoginUser.IsInRole("档案管理员;系统管理员;"))
            {
                this.uploadBtn.Visible = false;
                this.addBtn.Visible = false;
                this.destoryBtn.Visible = false;

                baseInfoList.Columns[12].Visible = false;
            }
        }

        public string CondtionString
        {
            get { return this.Condition.Value; }
        }

        private void Search()
        {
            int total;
            string condition1 = GetCondition1();
            string condition2 = GetCondition2();
            //缓存到页面隐藏字段
            this.Condition.Value = condition2;

            if (this.PageSize.Text == "")
                this.PageSize.Text = "15";
            pager.PageSize = int.Parse(this.PageSize.Text);
            List<ZHArchInfo> list = ZHArchInfoService.GetZHArchInfos(SystemContext.Current.LoginUser, condition1,
                                                                     condition2,
                                                                     pager.CurrentPageIndex, pager.PageSize, out total);

            foreach (GridViewRow gr in baseInfoList.Rows)
            {
                HtmlInputCheckBox cb = (HtmlInputCheckBox) gr.Cells[0].FindControl("chkItem");
                string id = cb.Attributes["value"].Split(',')[0];
                if (ViewState[id] != null)
                {
                    ViewState.Remove(id);
                }
            }

            // 获取GridView排序数据列及排序方向
            string sortExpression = this.baseInfoList.Attributes["SortExpression"];
            string sortDirection = this.baseInfoList.Attributes["SortDirection"];

            IQueryable<ZHArchInfo> queryableList;
            // 根据GridView排序数据列及排序方向设置显示的默认数据视图
            if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
            {
                //调用排序方法对当前页数据进行排序
                queryableList = (list.AsQueryable()).OrderUsingSortExpression(sortExpression + " " + sortDirection);
            }
            else
            {
                queryableList = list.AsQueryable();
            }

            //ZHArchInfos = queryableList;

            // GridView绑定并显示数据
            this.baseInfoList.DataSource = queryableList;
            this.baseInfoList.DataBind();

            pager.RecordCount = total;
        }

        protected void baseInfoList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
                
            //}
        }
        
        protected void DealCommand(object sender, GridViewCommandEventArgs e)
        {
            string commandName = e.CommandName;
            var paramIds = e.CommandArgument as string;
            if (commandName.Equals("DeleteArchInfo"))
            {
                if (paramIds != null)
                {
                    BaseInfoService.DeleteBaseInfo(paramIds.Split(',')[0]);
                    ArchInfoService.DeleteArchInfo(paramIds.Split(',')[1]);
                }
            }
            Search();
        }

        //列表的排序事件
        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            // 从事件参数获取排序数据列
            string sortExpression = e.SortExpression.ToString();
            // 假定为排序方向为“顺序”
            string sortDirection = "ASC";
            // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
            if (sortExpression == baseInfoList.Attributes["SortExpression"])
            {
                //获得下一次的排序状态
                sortDirection = (baseInfoList.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
            }
            // 重新设定GridView排序数据列及排序方向
            baseInfoList.Attributes["SortExpression"] = sortExpression;
            baseInfoList.Attributes["SortDirection"] = sortDirection;
            
            Search();
        }


        protected string GetCondition1()
        {
            string condition = "";

            //condition += string.Format(" and it.Type='{0}'", FormType);

            

            return condition;
        }

        protected string GetCondition2()
        {
            string condition = "";

            if (ddlBelongYear.SelectedValue != "")
            {
                condition += string.Format(" and it.BelongYear = '{0}'", ddlBelongYear.SelectedValue);
            }
            //if (ddlBelongMonth.SelectedValue != "")
            //{
            //    condition += string.Format(" and it.BelongMonth = '{0}'", ddlBelongMonth.SelectedValue);
            //}
            if (txtName.Text != "")
            {
                condition += string.Format(" and it.Name like '%{0}%'", txtName.Text.Trim());
            }
            if (ddlDestroy.SelectedValue != "")
            {
                condition += string.Format(" and it.IsDestroy = {0}", ddlDestroy.SelectedValue);
            }
            if (txtInitDateBegin.Text != "")
            {
                condition += string.Format(" and it.InitDate >= cast('{0}' as System.DateTime)", DateTime.Parse(txtInitDateBegin.Text));
            }
            if (txtInitDateEnd.Text != "")
            {
                condition += string.Format(" and it.InitDate <= cast('{0}' as System.DateTime)", DateTime.Parse(txtInitDateEnd.Text));
            }

            if (txtBeginTimeBegin.Text != "")
            {
                condition += string.Format(" and it.CustodyBeginDate >= cast('{0}' as System.DateTime)", DateTime.Parse(txtBeginTimeBegin.Text));
            }
            if (txtBeginTimeEnd.Text != "")
            {
                condition += string.Format(" and it.CustodyBeginDate <= cast('{0}' as System.DateTime)", DateTime.Parse(txtBeginTimeEnd.Text));
            }

            if (txtExpireTimeBegin.Text != "")
            {
                condition += string.Format(" and it.CustodyEndDate >= cast('{0}' as System.DateTime)", DateTime.Parse(txtExpireTimeBegin.Text));
            }
            if (txtExpireTimeEnd.Text != "")
            {
                condition += string.Format(" and it.CustodyEndDate <= cast('{0}' as System.DateTime)", DateTime.Parse(txtExpireTimeEnd.Text));
            }

            return condition;
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Search();
        }

        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void pager_PageChanged(object sender, EventArgs e)
        {
            Search();
        }
        
        protected void ExportClick(object sender, EventArgs e)
        {
            string condition1 = GetCondition1();
            string condition2 = GetCondition2();

            Dictionary<string, DataTable[]> forms = new Dictionary<string, DataTable[]>();
            List<DataTable> tables = ZHArchInfoService.GetZHArchInfoTable(SystemContext.Current.LoginUser,
                                                                          condition1,
                                                                          condition2);

            if (tables == null)
            {
                ClientHelper.Instance.Alert("导出记录数超过Excel的最大行数（65535），请先筛选数据，分多次导出，谢谢。");
                return;
            }

            forms.Add("综合资料信息", tables.ToArray());
            try
            {
                ClientHelper.Instance.ExportToExcel(forms, "综合资料信息");
            }
            catch (Exception ex)
            {
                LogHelper.LogException(ex);
            }

        }
    }
}